package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     出现问题： 并没创建交换机、队列、绑定关系

     出现问题的原因：只有当第一次连接上RabbitMQ时，发现没有这些东西才会创建

     解决方案：监听任一队列，创建成功后注释掉
     * @param message
     */
//    @RabbitListener(queues = "stock.release.queue")
//    public void handle(Message message){
//
//    }

    @Bean
    public Exchange stockEventExchange(){
        return new TopicExchange("stock-event-exchange", true, false);
    }

    @Bean
    public Queue stockReleaseQueue(){
        return new Queue("stock.release.queue", true, false, false);
    }

    @Bean
    public Queue stockDelayQueue(){
        Map<String,Object> args=new HashMap<>();
        args.put("x-dead-letter-exchange","stock-event-exchange");
        args.put("x-dead-letter-routing-key","stock.release");
        args.put("x-message-ttl",120000);
        Queue queue = new Queue("stock.delay.queue", true, false, false,args);
        return queue;
    }

    @Bean
    public Binding stockReleaseOrderBinding(){
        return new Binding("stock.release.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }

    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }



//    @PostConstruct
//    public void initRabbitTemplate(){
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            /**
//             * 只要消息抵达服务器，ack=true
//             * @param correlationData 消息唯一id
//             * @param ask 消息是否成功收到
//             * @param cause 失败的原因
//             */
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ask, String cause) {
//
//            }
//        });
//        //设置消息抵达队列的确认回调
//        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
//            /**
//             * 只要消息没有投递给指定队列，就触发这失败回调
//             * @param returnedMessage
//             */
//            @Override
//            public void returnedMessage(ReturnedMessage returnedMessage) {
//
//            }
//        });
//    }
}
